package org.auf.model.jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.LinkedList;

import org.apache.log4j.Logger;
import org.auf.model.dao.IChatEventDAO;
import org.auf.to.ChatEvent;
import org.auf.to.Event;

public class ChatEventDAOJDBC implements IChatEventDAO {
	
	static Logger log = Logger.getLogger(UserDAOJDBC.class.getName());

	@Override
	public boolean insertChatEvent(ChatEvent chatevent) {
		int updates=0;
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection db = cm.checkOut();
		
		try{
			PreparedStatement st = db.prepareStatement("INSERT INTO tblchatevent (id,event,user,message,date) values (?,?,?,?,?");
			st.setString(1, chatevent.getId());
			st.setString(2, chatevent.getEvent().getId());
			st.setString(3, chatevent.getUser().getId());
			st.setString(4, chatevent.getMessage());
			st.setDate(5, (Date) chatevent.getDate());
			updates =st.executeUpdate();
		
		}catch(Exception e){updates=-1;log.error("Error al generar la sentencia SQL y ejecutarla: "+e);}

		cm.checkIn(db);
		// TODO Auto-generated method stub
		return updates==1;
	}

	@Override
	public Collection<ChatEvent> selectChatEventByEvent(Event event) {
		Collection<ChatEvent> sol = new LinkedList<ChatEvent>();
		
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection db = cm.checkOut();
		
		try{
			PreparedStatement st = db.prepareStatement("SELECT * FROM tblchatevent WHERE event=? ORDER BY date DESC");
			st.setString(1, event.getId());
			ResultSet rs = st.executeQuery();
		
			if (rs.next()){
				ChatEvent ce = new ChatEvent();
				ce.setId( rs.getString("id"));
				ce.setEvent(EventDAOJDBC.getInstance().selectEvent(rs.getString("event")));
				ce.setUser(UserDAOJDBC.getInstance().selectUserByid(rs.getString("user")));
				ce.setDate(rs.getDate("date"));
				sol.add(ce);
			}
		
		}catch(Exception e){sol=null;log.error("Error al generar la sentencia SQL y ejecutarla: "+e);}

		cm.checkIn(db);
		// TODO Auto-generated method stub
		return sol;
	}

}
